﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace NeuralLib
{
    public class DisconnectedNetwork
    {
        private List<DisconnectedNeuron> _neurons;
        private List<Connection> _connections;

        public DisconnectedNetwork(List<DisconnectedNeuron> neurons, List<Connection> connections)
        {
            _neurons = neurons;
            _connections = connections;
        }

        public double[] Compute(double[] input)
        {
            var inputNeurons = _neurons.Where(n => n.Type == ENeuronType.NtInput).OrderBy(n => n.Id).ToList();
            for (int i = 0; i < inputNeurons.Count(); i++)
            {
                inputNeurons[i].Output = input[i];
                inputNeurons[i].IsActivated = true;
            }
            var outputNeurons = _neurons.Where(n => n.Type == ENeuronType.NtOutput).ToList();

            foreach (var neuron in outputNeurons)
            {
               
                SearchIn(neuron);
            }

            return outputNeurons.OrderBy(n => n.Id).Select(n => n.Output).ToArray();
        }

        private void SearchIn(DisconnectedNeuron neuron)
        {
            var connections = _connections.Where(c => c.OutputNeuron.Id == neuron.Id).ToList();
            if (connections.Count > 0)
            {
                var weights = connections.Select(c => c.Weight).ToArray();
                var inputs = new Double[connections.Count()];
                var neurons = connections.Select(c => c.InputNeuron).ToArray();
                for (var j = 0; j < neurons.Count(); j++)
                {
                    if (!neurons[j].IsActivated)
                        SearchIn(neurons[j]);
                    inputs[j] = neurons[j].Output;
                }
                neuron.Compute(inputs, weights);
            }
            else
            {
                neuron.IsActivated = true;
            }
        }
    }
}
